package org.light.reflecttable.daoimpl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import org.light.reflecttable.dao.DatabaseDao;
import org.light.reflecttable.domain.Database;

public class DatabaseDaoImpl implements DatabaseDao{
	public List<Database> listAllDatabases(Connection connection) throws Exception{
		try {
			if (connection != null) {
				String query = "show databases;";
				PreparedStatement ps = connection.prepareStatement(query);
				ResultSet result = ps.executeQuery();
				ArrayList<Database> list = new ArrayList<Database>();
				long serial = 1L;
				while(result.next()) {
					//Build the list object.
					Database table = new Database();
					table.setDatabaseName(result.getString(1));
					table.setActive(true);
					table.setId(serial);
					//Build the object list.
					list.add(table);
					serial ++;
				}
				return list;
			}
			return null;
		} catch (Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	public List<Database> listAllPgDatabases(Connection connection) throws Exception{
		try {
			if (connection != null) {
				String query = "SELECT datname FROM pg_database;";
				PreparedStatement ps = connection.prepareStatement(query);
				ResultSet result = ps.executeQuery();
				ArrayList<Database> list = new ArrayList<Database>();
				long serial = 1L;
				while(result.next()) {
					//Build the list object.
					Database table = new Database();
					table.setDatabaseName(result.getString("datname"));
					table.setActive(true);
					table.setId(serial);
					//Build the object list.
					list.add(table);
					serial ++;
				}
				return list;
			}
			return null;
		} catch (Exception e){
			e.printStackTrace();
			return null;
		}
	}
}
